package org.cms;


import com.atlassian.jira.rest.client.api.domain.Issue;
import com.atlassian.jira.rest.client.internal.json.IssueJsonParser;
import org.cms.dao.IDao;
import org.cms.entities.Event;
import org.codehaus.jettison.json.JSONArray;
import org.codehaus.jettison.json.JSONObject;

import javax.ejb.EJB;
import java.io.FileInputStream;
import java.io.InputStream;
import java.net.URL;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.util.List;
import java.util.logging.Logger;

/**
 *
 *
 */
public class JiraFacade implements ITaskService<Event> {

    private static final String ACCESS_TOKEN = "jmzEFvzUTbHGCP7UUbVrPA4BSUcHpnOg";


    Logger log = Logger.getLogger("JiraFacade");

    @EJB(beanName = "CheckInDao")
    IDao<Issue, String> taskDao;

    /**
     * Retrive a list of event for a specific user
     *
     * @return the list of Events
     * @throws java.io.IOException
     * @throws org.json.JSONException
     */
    @Override
    public List<Event> getUserTasks() throws Exception {

        URL namesUrl = this.getClass().getResource("/jira_name.json");
        URL schemaUrl = this.getClass().getResource("/jira_schema.json");


        String providedNames = new String(Files.readAllBytes(Paths.get(namesUrl.toURI())));
        String providedSchema = new String(Files.readAllBytes(Paths.get(schemaUrl.toURI())));

        JSONObject providedNamesJson = new JSONObject(providedNames);
        JSONObject providedSchemaJson = new JSONObject(providedSchema);

//        String response = new AtlassianOAuthClient("http://localhost:9090").makeAuthenticatedRequest("http://localhost:9090/rest/api/2/issue/CMSDEV-1", ACCESS_TOKEN);
        String response = new AtlassianOAuthClient("http://localhost:9090").makeAuthenticatedRequest("http://localhost:9090/rest/api/2/search?jql=assignee=hugo", ACCESS_TOKEN);

        JSONObject jsonObject = new JSONObject(response);

        JSONArray issuesArray = jsonObject.getJSONArray("issues");
        for (int i = 0; i < issuesArray.length(); i++) {
            JSONObject issueJson = issuesArray.getJSONObject(i);
            IssueJsonParser parser = new IssueJsonParser(providedNamesJson, providedSchemaJson);
            Issue issue = null;
            try {
                issue = parser.parse(issueJson);
            } catch (NullPointerException ex) {

            }

            System.out.println(issue.getSummary());

        }


        return null;

    }


}

